import { TreeItem } from '@ide/types/tree';

export function getContractNameByPath(path?:string):string|false {
  if (!path) {
    return false;
  }
  const res = path.match(/workspaces\/[\w-]+\/src\/([^/]+)/);
  if (res && res[1]) {
    return res[1];
  } else {
    return false;
  }
}

export function getParentPathByPath(path:string):string[] {
  const paths = [];
  let newp = path;
  while (/src\/[\w\W]+/.test(newp)){
    const res = newp.match(/([\w\W]+)\/[^\/]+$/);
    if(res&&res?.length>1){
      newp = res[1];
      paths.push(newp);
    }else{
      newp = ''
    }
  }
  return paths
}

export function downlaodFileByPath(path:string) {
  // var path = $(this).data("path");
  // var $iframe = $('<iframe style="display:none;" src="'+path+'"></iframe>');
  // $('body').append($iframe);
  // const a = document.createElement('a');
  // a.setAttribute('target', '_blank');
  // a.setAttribute('href', path);
  // a.setAttribute('download', path);
  // a.click();
  // setTimeout(function () {
  //   a.remove();
  // }, 10);
  const iframe = document.createElement('iframe');
  iframe.setAttribute('style', 'display:none;');
  iframe.setAttribute('src', path);
  iframe.setAttribute('download', path);
  document.body.appendChild(iframe);
  setTimeout(function () {
    iframe.remove();
  }, 2000);
}

export function setLocalStorage(action:string, dir:string, func:string, value:any) {
  const storagename = action + '_params';
  let storagevalue = JSON.parse(localStorage.getItem(storagename) || '{}');
  storagevalue = storagevalue || {};
  storagevalue[dir + '-' + func] = {
    overtime: new Date().getTime() + 3 * 24 * 60 * 60 * 1000,
    value
  };
  localStorage.setItem(storagename, JSON.stringify(storagevalue));
}
export function getLocalStorage(action:string, dir:string, func:string) {
  const storagename = action + '_params';
  let storagevalue = JSON.parse(localStorage.getItem(storagename) || '{}');
  storagevalue = storagevalue || {};
  const v = storagevalue[dir + '-' + func];
  if (v && v.overtime && v.overtime > new Date().getTime()) {
    return v.value;
  } else {
    return undefined;
  }
  // return localStorage.getItem(action+'-'+dir+'-'+func);
}

export function removeLocalStorage(action:string, dir:string, func:string) {
  const storagename = action + '_params';
  let storagevalue = JSON.parse(localStorage.getItem(storagename) || '{}');
  storagevalue = storagevalue || {};
  if (dir && func) {
    delete storagevalue[dir + '-' + func];
  } else {
    storagevalue = {};
  }
  localStorage.setItem(storagename, JSON.stringify(storagevalue));
}

export function removeActionLocalStorage(action:string) {
  const storagename = action + '_params';
  localStorage.removeItem(storagename);
}

export function debounce(fn:(args:any)=>void, wait:number) {
  let timer:any = null;
  return function(...args:any) {
    if (timer !== null) {
      clearTimeout(timer);
    }

    timer = setTimeout(() => {
      fn.apply({}, args);
      timer = null;
    }, wait);
  };
}

export function GetRequest() {
  const url = location.search; // 获取url中"?"符后的字串
  const theRequest: any = {};
  if (url.indexOf('?') !== -1) {
    const str = url.substr(1);
    const strs = str.split('&');
    strs.forEach(item => {
      const param = item.split('=');
      theRequest[param[0]] = param[1];
    });
  }
  return theRequest;
}

export function formatTree(files: any[]): TreeItem[] {
  return files.map(item => {
    const { name, type, children, path, isGOAPI, isParent, canNotRenameAble } = item;
    return {
      id: path,
      name: name ?? 'root',
      content: name ?? 'root',
      type: type === 'f' ? 'file' : 'folder',
      path,
      editable: !isGOAPI,
      isParent,
      children: children.length ? formatTree(children) : undefined,
      canNotRenameAble
    };
  });
}

export const getTreeNode = (path: string, tree: TreeItem[]): TreeItem | null => {
  for (let i = 0; i < tree.length; i++) {
    const item = tree[i];
    if (item.path === path) {
      return item;
    }
    if (item.children) {
      const node = getTreeNode(path, item.children);
      if (node) {
        return node;
      }
    }
  }
  return null;
};
